<?php

namespace app\models;

use yii\base\Model;

class LoginForm extends Model
{
    public $account;
    public $password;
    public $rememberMe = true;

    private $_manager = false;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            // username and password are both required
            [['account', 'password'], 'required'],
            // rememberMe must be a boolean value
            ['rememberMe', 'boolean'],
            // password is validated by validatePassword()
            ['password', 'validatePassword'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
//            $this->_manager = ManagerActiveRecord::find()->where(['account' => $this->account, 'password' => md5($this->password)])->one();
            $this->_manager = Manager::validatePassword($this->account, $this->password);

            if (!isset($this->_manager)) {
                $this->addError($attribute, 'ERROR');
            }
        }
    }

    /**
     * Logs in a user using the provided username and password.
     * @return boolean whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            Manager::setCurrentManager($this->_manager);
            return true;
        }
        return false;
    }
}